package com.example.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.TemplateMapper;
import com.example.mapper.UserAndRoleMapper;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.Role;
import com.example.pojo.entity.Template;
import com.example.pojo.entity.UserAndRole;
import com.example.pojo.vo.ApproverVO;
import com.example.service.TemplateService;
import com.example.utils.HttpsUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/12
 */
@Slf4j
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页获取审批模版
     */
    public Page<Template> selectPage(Integer pageNum, Integer pageSize) {
        QueryWrapper<Template> queryWrapper = new QueryWrapper<Template>()
                .eq("is_deleted", 0);
        Page<Template> page = templateMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        List<Template> records = page.getRecords();
        for (Template record : records) {
            StringBuilder sb = new StringBuilder("");
            String[] userIds = record.getPerson().split(",");
            for (int i = 1; i <= userIds.length; i++) {
                Admin admin = adminMapper.selectById(Integer.parseInt(userIds[i-1]));
                sb.append(admin.getName() + " ");
            }
            record.setPerson(sb.toString());
        }
        page.setRecords(records);
        return page;
    }

    /**
     * 删除审批信息，同时删除部署的流程模版
     */
    @Transactional
    public void delete(Integer id) {
        Template template = templateMapper.selectById(id);
        template.setIsDeleted(1);
        templateMapper.updateById(template);
    }

    /**
     * 获取审批人数据1
     */
    public List<ApproverVO> getApprover() {
        MPJLambdaWrapper<Admin> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper
                .selectAll(Admin.class)
                .innerJoin(UserAndRole.class, UserAndRole::getUserId, Admin::getId)
                .innerJoin(Role.class, Role::getId, UserAndRole::getRoleId)
                .eq(Role::getRoleValue, "approver");

        List<Admin> adminList = adminMapper.selectList(mpjLambdaWrapper);
        log.info("审批人列表为{}", adminList);

        //只返回 id 和 name
        return adminList.stream().map(admin -> new ApproverVO(admin.getId()+"-"+admin.getName(), admin.getId()+"-"+admin.getName())).collect(Collectors.toList());
    }

    //根据模版id获取模版信息
    public Template selectById(Integer id) {
        Template template = templateMapper.selectById(id);
        String[] userIds = template.getPerson().split(",");
        for (int i = 1; i <= userIds.length; i++) {
            Admin admin = adminMapper.selectById(Integer.parseInt(userIds[i-1]));
            if (i == 1) {
                template.setPerson1(admin.getName());
            }
            if (i == 2) {
                template.setPerson2(admin.getName());
            }
            if (i == 3) {
                template.setPerson3(admin.getName());
            }
        }
        return template;
    }

    public void setStatus(Template template) {
        templateMapper.update(new UpdateWrapper<Template>()
                .set(ObjectUtil.isNotEmpty(template.getId()), "status", template.getStatus())
                .eq("id", template.getId()));
    }

    /**
     * 新增审批模版
     */
    public void addTemplate(Template template) {
        String person = "";
        String per = "";
        if (ObjectUtil.isNotEmpty(template.getPerson1())) {
            String[] split = template.getPerson1().split("-");
            person += split[0] + ",";
            per += split[1] + "-";
        }
        if (ObjectUtil.isNotEmpty(template.getPerson2())) {
            String[] split = template.getPerson2().split("-");
            person += split[0] + ",";
            per += split[1] + "-";
        }
        if (ObjectUtil.isNotEmpty(template.getPerson3())) {
            String[] split = template.getPerson3().split("-");
            person += split[0] +",";
            per += split[1] + "-";
        }
        Map<String, String> map = new HashMap<>();
        map.put("persons", per);
        map.put("name", template.getName());
        String result = HttpsUtil.sendGet("http://localhost:9091/engine/deploy", map);

        String procDefId = result.split("-")[0];
        String procDepId = result.split("-")[1];

        template.setProcDefId(procDefId);
        template.setProcDepId(procDepId);
        template.setPerson(person);
        template.setVersion(0);
        template.setIsDeleted(0);
        templateMapper.insert(template);
    }
}
